Initialising notebook

In [2]:
import pandas as pd
import pylab
import matplotlib.pyplot as plt
import numpy as np
import calendar
import seaborn as sns

file_name = 'tmdb_5000_movies.csv'
tmdb_5000 = pd.read_csv(file_name)

pd.set_option('display.max_columns', None)  
pd.set_option('display.max_rows', None)  

pd.set_option('display.float_format', lambda x: '%.2f' % x)
tmdb_5000['release_date'] = pd.to_datetime(tmdb_5000['release_date'], errors='coerce')
main_columns = ['budget','genres','keywords','original_language','original_title','overview','production_companies','production_countries','spoken_languages','tagline','title','revenue','runtime','vote_average','vote_count','popularity','release_date']
tmdb_5000 = tmdb_5000.loc[:, main_columns]
In [3]:
duplicate_rows = tmdb_5000[tmdb_5000.duplicated()]
num_duplicate_rows = len(duplicate_rows)
In [4]:
tmdb_5000['budget'] = tmdb_5000['budget'].replace(0 , np.nan)
tmdb_5000['revenue'] = tmdb_5000['revenue'].replace(0 , np.nan)
tmdb_5000['runtime'] = tmdb_5000['runtime'].replace(0.00 , np.nan)
tmdb_5000['vote_average'] = tmdb_5000['vote_average'].replace(0.00 , np.nan)
tmdb_5000['vote_count'] = tmdb_5000['vote_count'].replace(0 , np.nan)
tmdb_5000['popularity'] = tmdb_5000['popularity'].replace(0.00 , np.nan)
tmdb_5000['release_date'] = tmdb_5000['release_date'].replace(0 , np.nan)
In [5]:
tmdb_5000.sort_values(by='budget', ascending=True)
tmdb_5000 = tmdb_5000[tmdb_5000['budget'] >= 7000]
tmdb_5000.sort_values(by='budget', ascending=True).head()
Out[5]:
budget genres keywords original_language original_title overview production_companies production_countries spoken_languages tagline title revenue runtime vote_average vote_count popularity release_date
4796 7000.00 [{"id": 878, "name": "Science Fiction"}, {"id"... [{"id": 1448, "name": "distrust"}, {"id": 2101... en Primer Friends/fledgling entrepreneurs invent a devic... [{"name": "Thinkfilm", "id": 446}] [{"iso_3166_1": "US", "name": "United States o... [{"iso_639_1": "en", "name": "English"}] What happens if it actually works? Primer 424760.00 77.00 6.90 658.00 23.31 2004-10-08
4696 8000.00 [{"id": 18, "name": "Drama"}, {"id": 10749, "n... [{"id": 237, "name": "gay"}, {"id": 1025, "nam... en Weekend After a drunken house party with his straight ... [{"name": "EM Media", "id": 1917}, {"name": "T... [{"iso_3166_1": "GB", "name": "United Kingdom"}] [{"iso_639_1": "en", "name": "English"}] A (sort of) love story between two guys over a... Weekend 469947.00 96.00 7.40 163.00 1.04 2011-09-22
4799 9000.00 [{"id": 35, "name": "Comedy"}, {"id": 10749, "... [] en Newlyweds A newlywed couple's honeymoon is upended by th... [] [] [] A newlywed couple's honeymoon is upended by th... Newlyweds NaN 85.00 5.90 5.00 0.64 2011-12-26
4724 10000.00 [{"id": 18, "name": "Drama"}, {"id": 14, "name... [{"id": 1009, "name": "baby"}, {"id": 1852, "n... en Eraserhead Henry Spencer tries to survive his industrial ... [{"name": "American Film Institute (AFI)", "id... [{"iso_3166_1": "US", "name": "United States o... [{"iso_639_1": "en", "name": "English"}] Where your nightmares end... Eraserhead 7000000.00 89.00 7.50 485.00 20.40 1977-03-19
4788 12000.00 [{"id": 27, "name": "Horror"}, {"id": 35, "nam... [{"id": 237, "name": "gay"}, {"id": 900, "name... en Pink Flamingos Notorious Baltimore criminal and underground f... [{"name": "Dreamland Productions", "id": 407}] [{"iso_3166_1": "US", "name": "United States o... [{"iso_639_1": "en", "name": "English"}] An exercise in poor taste. Pink Flamingos 6000000.00 93.00 6.20 110.00 4.55 1972-03-12
In [6]:
tmdb_5000.sort_values(by='revenue', ascending=True)
tmdb_5000 = tmdb_5000[tmdb_5000['revenue'] >= 3000]
tmdb_5000.sort_values(by='revenue', ascending=True).head() 
Out[6]:
budget genres keywords original_language original_title overview production_companies production_countries spoken_languages tagline title revenue runtime vote_average vote_count popularity release_date
4065 2100000.00 [{"id": 18, "name": "Drama"}, {"id": 80, "name... [{"id": 40865, "name": "new york state"}, {"id... en Mi America A hate-crime has been committed in a the small... [{"name": "Industrial House Films", "id": 65589}] [{"iso_3166_1": "US", "name": "United States o... [{"iso_639_1": "es", "name": "Espa\u00f1ol"}, ... NaN Mi America 3330.00 126.00 NaN NaN 0.04 2015-10-16
1999 25000000.00 [{"id": 14, "name": "Fantasy"}, {"id": 12, "na... [{"id": 212, "name": "london england"}, {"id":... en The Adventurer: The Curse of the Midas Box 17-year-old Mariah Mundi's life is turned upsi... [{"name": "Matador Pictures", "id": 707}, {"na... [{"iso_3166_1": "BE", "name": "Belgium"}, {"is... [{"iso_639_1": "en", "name": "English"}] The new name for adventure. The Adventurer: The Curse of the Midas Box 6399.00 99.00 5.10 73.00 8.84 2013-12-05
4399 1000000.00 [{"id": 18, "name": "Drama"}, {"id": 14, "name... [{"id": 3298, "name": "hallucination"}, {"id":... en Special A lonely metermaid has a psychotic reaction to... [{"name": "Rival Pictures", "id": 2830}] [{"iso_3166_1": "US", "name": "United States o... [{"iso_639_1": "en", "name": "English"}] NaN Special 7202.00 81.00 6.60 32.00 1.26 2006-01-30
3121 10000000.00 [{"id": 35, "name": "Comedy"}] [] en Janky Promoters Two shady concert promoters get into hot water... [{"name": "Cube Vision", "id": 2780}, {"name":... [{"iso_3166_1": "US", "name": "United States o... [{"iso_639_1": "en", "name": "English"}] NaN Janky Promoters 9069.00 85.00 7.00 5.00 1.73 2009-10-16
4772 31192.00 [{"id": 18, "name": "Drama"}, {"id": 28, "name... [{"id": 9826, "name": "murder"}, {"id": 10123,... en Down Terrace After serving jail time for a mysterious crime... [] [{"iso_3166_1": "GB", "name": "United Kingdom"}] [{"iso_639_1": "en", "name": "English"}] You're only as good as the people you know. Down Terrace 10000.00 89.00 6.30 26.00 1.33 2009-09-01
In [7]:
tmdb_5000 = tmdb_5000.drop(2384, axis='index')
In [8]:
columns_to_keep = ['budget','revenue','runtime','vote_average','vote_count','popularity','release_date']
sum_stats1 = tmdb_5000.loc[:, columns_to_keep]
In [9]:
test_drop_nulls = pd.DataFrame(tmdb_5000['budget'])
test_drop_nulls = test_drop_nulls.dropna()
print(test_drop_nulls.isnull().sum())
budget    0
dtype: int64
In [10]:
test_drop_nulls
test_drop_nulls2 = pd.concat([test_drop_nulls], ignore_index=True)
test_drop_nulls2.head()
Out[10]:
budget
0 237000000.00
1 300000000.00
2 245000000.00
3 250000000.00
4 260000000.00

Runnign code for interactive map

In [11]:
!pip install plotly
Requirement already satisfied: plotly in /Users/ines.delannoy/anaconda3/lib/python3.11/site-packages (5.9.0)
Requirement already satisfied: tenacity>=6.2.0 in /Users/ines.delannoy/anaconda3/lib/python3.11/site-packages (from plotly) (8.2.2)
In [12]:
import ast

# Convert only non-list entries using ast.literal_eval
tmdb_5000['production_countries'] = tmdb_5000['production_countries'].apply(
    lambda x: ast.literal_eval(x) if isinstance(x, str) else x
)

# Extract country names from the list, if present
tmdb_5000['production_countries'] = tmdb_5000['production_countries'].apply(
    lambda x: [i['name'] if isinstance(i, dict) else i for i in x] if isinstance(x, list) and x else x
)
In [13]:
s = tmdb_5000.apply(lambda x: pd.Series(x['production_countries']),axis=1).stack().reset_index(level=1, drop=True)
s.name = 'countries'
In [14]:
con_df = tmdb_5000.drop('production_countries', axis=1).join(s)
con_df = pd.DataFrame(con_df['countries'].value_counts())
con_df['country'] = con_df.index
con_df.columns = ['num_movies', 'country']
con_df = con_df.reset_index(drop=True)
con_df.head(10)
Out[14]:
num_movies country
0 2895 United States of America
1 431 United Kingdom
2 231 Germany
3 195 France
4 161 Canada
5 77 Australia
6 48 Italy
7 43 Spain
8 40 Japan
9 37 China
In [15]:
con_df = con_df[con_df['country'] != 'United States of America']
In [16]:
import plotly.graph_objs as go
import plotly.express as px



fig = px.choropleth(
    tmdb_5000,
    locations=con_df['country'],
    locationmode='country names',
    color=con_df['num_movies'],
    title='Movies released per country (excluding US) in The Movie Database 5000',
    color_continuous_scale='viridis'
)

fig.update_layout(
    width=1000,  
    height=800  
)

fig.show()
In [21]:
!jupyter nbconvert --to html "INTERACTIVE PLOT MAP.ipynb"
[NbConvertApp] WARNING | pattern 'INTERACTIVEPLOTMAP.ipynb' matched no files
This application is used to convert notebook files (*.ipynb)
        to various other formats.

        WARNING: THE COMMANDLINE INTERFACE MAY CHANGE IN FUTURE RELEASES.

Options
=======
The options below are convenience aliases to configurable class-options,
as listed in the "Equivalent to" description-line of the aliases.
To see all configurable class-options for some <cmd>, use:
    <cmd> --help-all

--debug
    set log level to logging.DEBUG (maximize logging output)
    Equivalent to: [--Application.log_level=10]
--show-config
    Show the application's configuration (human-readable format)
    Equivalent to: [--Application.show_config=True]
--show-config-json
    Show the application's configuration (json format)
    Equivalent to: [--Application.show_config_json=True]
--generate-config
    generate default config file
    Equivalent to: [--JupyterApp.generate_config=True]
-y
    Answer yes to any questions instead of prompting.
    Equivalent to: [--JupyterApp.answer_yes=True]
--execute
    Execute the notebook prior to export.
    Equivalent to: [--ExecutePreprocessor.enabled=True]
--allow-errors
    Continue notebook execution even if one of the cells throws an error and include the error message in the cell output (the default behaviour is to abort conversion). This flag is only relevant if '--execute' was specified, too.
    Equivalent to: [--ExecutePreprocessor.allow_errors=True]
--stdin
    read a single notebook file from stdin. Write the resulting notebook with default basename 'notebook.*'
    Equivalent to: [--NbConvertApp.from_stdin=True]
--stdout
    Write notebook output to stdout instead of files.
    Equivalent to: [--NbConvertApp.writer_class=StdoutWriter]
--inplace
    Run nbconvert in place, overwriting the existing notebook (only
            relevant when converting to notebook format)
    Equivalent to: [--NbConvertApp.use_output_suffix=False --NbConvertApp.export_format=notebook --FilesWriter.build_directory=]
--clear-output
    Clear output of current file and save in place,
            overwriting the existing notebook.
    Equivalent to: [--NbConvertApp.use_output_suffix=False --NbConvertApp.export_format=notebook --FilesWriter.build_directory= --ClearOutputPreprocessor.enabled=True]
--no-prompt
    Exclude input and output prompts from converted document.
    Equivalent to: [--TemplateExporter.exclude_input_prompt=True --TemplateExporter.exclude_output_prompt=True]
--no-input
    Exclude input cells and output prompts from converted document.
            This mode is ideal for generating code-free reports.
    Equivalent to: [--TemplateExporter.exclude_output_prompt=True --TemplateExporter.exclude_input=True --TemplateExporter.exclude_input_prompt=True]
--allow-chromium-download
    Whether to allow downloading chromium if no suitable version is found on the system.
    Equivalent to: [--WebPDFExporter.allow_chromium_download=True]
--disable-chromium-sandbox
    Disable chromium security sandbox when converting to PDF..
    Equivalent to: [--WebPDFExporter.disable_sandbox=True]
--show-input
    Shows code input. This flag is only useful for dejavu users.
    Equivalent to: [--TemplateExporter.exclude_input=False]
--embed-images
    Embed the images as base64 dataurls in the output. This flag is only useful for the HTML/WebPDF/Slides exports.
    Equivalent to: [--HTMLExporter.embed_images=True]
--sanitize-html
    Whether the HTML in Markdown cells and cell outputs should be sanitized..
    Equivalent to: [--HTMLExporter.sanitize_html=True]
--log-level=<Enum>
    Set the log level by value or name.
    Choices: any of [0, 10, 20, 30, 40, 50, 'DEBUG', 'INFO', 'WARN', 'ERROR', 'CRITICAL']
    Default: 30
    Equivalent to: [--Application.log_level]
--config=<Unicode>
    Full path of a config file.
    Default: ''
    Equivalent to: [--JupyterApp.config_file]
--to=<Unicode>
    The export format to be used, either one of the built-in formats
            ['asciidoc', 'custom', 'html', 'latex', 'markdown', 'notebook', 'pdf', 'python', 'rst', 'script', 'slides', 'webpdf']
            or a dotted object name that represents the import path for an
            ``Exporter`` class
    Default: ''
    Equivalent to: [--NbConvertApp.export_format]
--template=<Unicode>
    Name of the template to use
    Default: ''
    Equivalent to: [--TemplateExporter.template_name]
--template-file=<Unicode>
    Name of the template file to use
    Default: None
    Equivalent to: [--TemplateExporter.template_file]
--theme=<Unicode>
    Template specific theme(e.g. the name of a JupyterLab CSS theme distributed
    as prebuilt extension for the lab template)
    Default: 'light'
    Equivalent to: [--HTMLExporter.theme]
--sanitize_html=<Bool>
    Whether the HTML in Markdown cells and cell outputs should be sanitized.This
    should be set to True by nbviewer or similar tools.
    Default: False
    Equivalent to: [--HTMLExporter.sanitize_html]
--writer=<DottedObjectName>
    Writer class used to write the
                                        results of the conversion
    Default: 'FilesWriter'
    Equivalent to: [--NbConvertApp.writer_class]
--post=<DottedOrNone>
    PostProcessor class used to write the
                                        results of the conversion
    Default: ''
    Equivalent to: [--NbConvertApp.postprocessor_class]
--output=<Unicode>
    overwrite base name use for output files.
                can only be used when converting one notebook at a time.
    Default: ''
    Equivalent to: [--NbConvertApp.output_base]
--output-dir=<Unicode>
    Directory to write output(s) to. Defaults
                                  to output to the directory of each notebook. To recover
                                  previous default behaviour (outputting to the current
                                  working directory) use . as the flag value.
    Default: ''
    Equivalent to: [--FilesWriter.build_directory]
--reveal-prefix=<Unicode>
    The URL prefix for reveal.js (version 3.x).
            This defaults to the reveal CDN, but can be any url pointing to a copy
            of reveal.js.
            For speaker notes to work, this must be a relative path to a local
            copy of reveal.js: e.g., "reveal.js".
            If a relative path is given, it must be a subdirectory of the
            current directory (from which the server is run).
            See the usage documentation
            (https://nbconvert.readthedocs.io/en/latest/usage.html#reveal-js-html-slideshow)
            for more details.
    Default: ''
    Equivalent to: [--SlidesExporter.reveal_url_prefix]
--nbformat=<Enum>
    The nbformat version to write.
            Use this to downgrade notebooks.
    Choices: any of [1, 2, 3, 4]
    Default: 4
    Equivalent to: [--NotebookExporter.nbformat_version]

Examples
--------

    The simplest way to use nbconvert is

            > jupyter nbconvert mynotebook.ipynb --to html

            Options include ['asciidoc', 'custom', 'html', 'latex', 'markdown', 'notebook', 'pdf', 'python', 'rst', 'script', 'slides', 'webpdf'].

            > jupyter nbconvert --to latex mynotebook.ipynb

            Both HTML and LaTeX support multiple output templates. LaTeX includes
            'base', 'article' and 'report'.  HTML includes 'basic', 'lab' and
            'classic'. You can specify the flavor of the format used.

            > jupyter nbconvert --to html --template lab mynotebook.ipynb

            You can also pipe the output to stdout, rather than a file

            > jupyter nbconvert mynotebook.ipynb --stdout

            PDF is generated via latex

            > jupyter nbconvert mynotebook.ipynb --to pdf

            You can get (and serve) a Reveal.js-powered slideshow

            > jupyter nbconvert myslides.ipynb --to slides --post serve

            Multiple notebooks can be given at the command line in a couple of
            different ways:

            > jupyter nbconvert notebook*.ipynb
            > jupyter nbconvert notebook1.ipynb notebook2.ipynb

            or you can specify the notebooks list in a config file, containing::

                c.NbConvertApp.notebooks = ["my_notebook.ipynb"]

            > jupyter nbconvert --config mycfg.py

To see all available configurables, use `--help-all`.

In [ ]: